package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.GlobalType;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;

import java.io.PrintWriter;

import com.ccp.dev.system.service.DictionaryService;
import com.ccp.dev.system.service.GlobalTypeService;
import net.sf.json.JSONObject;

import java.nio.charset.StandardCharsets;

import com.ccp.dev.qbdms.model.WZbztkb;
import com.ccp.dev.qbdms.service.WZbztkbService;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;

import java.util.ArrayList;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 * 子标准条款 信息操作处理控制器
 *
 * @author 王明亮
 * @date 2020-05-13 12:17:10
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "子标准条款")
@RequestMapping("/qbdms/wZbztkb")
public class WZbztkbController extends SysBaseController {
    @Resource
    private WZbztkbService wZbztkbService;
    @Resource
    private GlobalTypeService globalTypeService;
    @Resource
    private DictionaryService dictionaryService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-05-13 12:17:10
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "跳转到子标准条款首页", exectype = "页面跳转日志")
    public String viewList() {
        return "wZbztkb/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-05-13 12:17:10
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "附带检索条件的分页查询子标准条款", detail = "查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        GlobalType globalType = globalTypeService.getByDictNodeKey("zbztk");
        String typeId = globalType.getTypeId();
        queryFilter.addFilter("typeid", typeId);
        //分页数据
        List<WZbztkb> pageDatas = wZbztkbService.queryList(queryFilter);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-05-13 12:17:10
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "跳转到子标准条款新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
        String dicid = RequestUtil.getString(request, "dicid");
        modelMap.put("dicid", dicid);
        List<Dictionary> bztkList = dictionaryService.getDicByNodeKey("bztk", false);
        modelMap.put("bztkList", JSON.toJSONString(bztkList));
        return "wZbztkb/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wZbztkb 保存的对象
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-05-13 12:17:10
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description = "保存子标准条款数据", detail = "<#if isAdd>新增<#else>编辑</#if>子标准条款数据<#if success>成功<#else>失败</#if>")
    public Object save(@RequestBody WZbztkb wZbztkb) {
        String id = wZbztkb.getDicid();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd", true);
            //新增操作
            //新增数据前生成随机Dicid
            wZbztkb.setDicid(UUIDUtils.getUUIDFor32());
            GlobalType globalType = globalTypeService.getByDictNodeKey("zbztk");
            String typeId = globalType.getTypeId();
            wZbztkb.setParentid(typeId);
            wZbztkb.setTypeid(typeId);
            wZbztkb.setNodepath(typeId + "." + wZbztkb.getDicid() + ".");
            result = wZbztkbService.add(wZbztkb);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            //修改操作
            result = wZbztkbService.update(wZbztkb);
        }
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-05-13 12:17:10
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description = "跳转到子标准条款详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request, ModelMap modelMap) {
        String dicid = RequestUtil.getString(request, "dicid");
        modelMap.put("dicid", dicid);
        return "wZbztkb/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"dicid"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-05-13 12:17:10
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description = "根据主键id查询子标准条款的一条数据", detail = "根据主键id查询子标准条款的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String dicid) {
        WZbztkb wZbztkb = wZbztkbService.getOneById(dicid);
        if (null == wZbztkb) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("get.success", wZbztkb);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"dicid"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-05-13 12:17:10
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "根据主键ID删除子标准条款数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String dicid) {
        if (StringUtil.isEmpty(dicid)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        int result = wZbztkbService.delByIdArray(dicid.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
     * 功能描述: 跳转到导入页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description = "跳转到子标准条款导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wZbztkb/import";
    }

    /**
     * 功能描述: 导出子标准条款数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-05-13 12:17:10
     */
    @RequestMapping("/exportData")
    @Action(description = "导出子标准条款数据信息", detail = "导出子标准条款数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        if (BeanUtils.isNotEmpty(id) && id.length != 0) {
            queryFilter.put("byId", true);
            queryFilter.put("id", id);
        } else {
            queryFilter.put("byId", false);
        }
        SysAuditThreadLocalHolder.putParamerter("success", true);
        Excel excel = new Excel();
        String fileName = "WZbztkb";//导出的文件名称
        excel.sheet().sheetName("sheet");// 重命名当前处于工作状态的表的名称
        List<String> titleList = new ArrayList<>();
        titleList.add("dicid");
        titleList.add("typeid");
        titleList.add("itemkey");
        titleList.add("itemname");
        titleList.add("itemvalue");
        titleList.add("description");
        titleList.add("sn");
        titleList.add("nodepath");
        titleList.add("parentid");
        excel.row(0, 0).value(titleList.toArray());
        excel.row(0, 0).font(new IFontEditor() {
            // 设置字体
            @Override
            public void updateFont(Font font) {
                font.boldweight(BoldWeight.BOLD);// 粗体
            }
        }).bgColor(Color.GREY_25_PERCENT).width(3500);
        excel.row(0, 1).width(3500);
        excel.row(0, 2).width(3500);
        excel.row(0, 3).width(3500);
        excel.row(0, 4).width(3500);
        //设置列的数据格式
        excel.sheet().setDefaultColumnStyle(0, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(1, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(2, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(3, DataFormat.TEXT);
        ExcelUtil.downloadExcel(wZbztkbService.exportExcel(excel, queryFilter), fileName, response);
    }

    /**
     * 导入资源文件
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/importData")
    public void importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile multipartFile = request.getFile("file");
        PrintWriter writer = response.getWriter();
        try {
            String fileName = multipartFile.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            //读取excel文件，并获取每行的数据
            ExcelReader excelReader = new ExcelReader();
            TableEntity excelEntity = excelReader.readFile(multipartFile.getInputStream());
            List<DataEntity> rowDataEntityList = excelEntity.getDataEntityList();

            List<WZbztkb> listToInsert = new ArrayList<>();
            for (DataEntity dataEntity : rowDataEntityList) {
                //获取每列的数据
                List<FieldEntity> fieldEntityList = dataEntity.getFieldEntityList();
                WZbztkb dataToInsert = new WZbztkb();
                int i = 0;
                //根据列的顺序，给相应的对象赋值
                for (FieldEntity fieldEntity : fieldEntityList) {
                    //if(i==0){
                    //dataToInsert.setName(fieldEntity.getValue());
                    //}
                    i++;
                }
                dataToInsert.setDicid(UUIDUtils.getUUIDFor32());
                listToInsert.add(dataToInsert);
            }
            wZbztkbService.addList(listToInsert);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("operation.success"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            JSONObject json = JSONObject.fromObject(getResultDataError("operation.failure"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        }
    }


}
